package com.example.androidproject.online.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import com.example.androidproject.databinding.ItemOnlineBinding;
import com.example.androidproject.sqlite.UserRepository;

public class OnlineAdapter extends RecyclerView.Adapter<OnlineAdapter.ViewHolder> {
    private ArrayList<UserRepository.User> list;
    private ItemClickListener listener;

    public OnlineAdapter(ArrayList<UserRepository.User> list, ItemClickListener listener) {
        this.list = list;
        this.listener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ItemOnlineBinding binding =ItemOnlineBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        UserRepository.User user = list.get(position);
        holder.bind(user);
    }

    @Override
    public int getItemCount() {
        return list==null?0:list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private ItemOnlineBinding binding;
        public ViewHolder(ItemOnlineBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
        public void bind(UserRepository.User user){
            binding.username.setText(user.getUsername()+"");
            binding.ipText.setText("(ip:"+user.getUserIp()+")");
            binding.linkCard.setOnClickListener(v->{
                listener.clickEvent(user);
            });

        }
    }

    public void update(ArrayList<UserRepository.User> list){
        this.list = list;
        notifyDataSetChanged();
    }

    public interface ItemClickListener{
        void clickEvent(UserRepository.User user);
    }
}
